import { Request, Response } from 'express';
import { Category } from '../models/Category';

// 获取所有分类
export const getCategories = async (req: Request, res: Response) => {
  try {
    const categories = await Category.find();
    res.json(categories);
  } catch (error) {
    res.status(500).json({ message: '获取分类列表失败', error });
  }
};

// 获取单个分类
export const getCategory = async (req: Request, res: Response) => {
  try {
    const category = await Category.findById(req.params.id);
    if (!category) {
      return res.status(404).json({ message: '分类不存在' });
    }
    res.json(category);
  } catch (error) {
    res.status(500).json({ message: '获取分类失败', error });
  }
};

// 创建分类
export const createCategory = async (req: Request, res: Response) => {
  try {
    const category = new Category(req.body);
    await category.save();
    res.status(201).json({
      message: '创建分类成功',
      category
    });
  } catch (error) {
    res.status(500).json({ message: '创建分类失败', error });
  }
};

// 更新分类
export const updateCategory = async (req: Request, res: Response) => {
  try {
    const category = await Category.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );
    
    if (!category) {
      return res.status(404).json({ message: '分类不存在' });
    }
    
    res.json({
      message: '更新分类成功',
      category
    });
  } catch (error) {
    res.status(500).json({ message: '更新分类失败', error });
  }
};

// 删除分类
export const deleteCategory = async (req: Request, res: Response) => {
  try {
    const category = await Category.findByIdAndDelete(req.params.id);
    
    if (!category) {
      return res.status(404).json({ message: '分类不存在' });
    }
    
    res.json({ message: '删除分类成功' });
  } catch (error) {
    res.status(500).json({ message: '删除分类失败', error });
  }
}; 